All files / src/services api.ts

71.18% Statements 84/118
55.95% Branches 47/84
71.42% Functions 15/21
71.68% Lines 81/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300    3x 3x 3x 3x   3x                                   3x           3x         3x     6x 6x 6x 4x       6x             6x   6x       6x                 6x               3x 2x   4x     4x                         4x       2x   2x 2x 1x 1x 1x 1x       1x 1x 1x         2x 1x 1x       2x                       2x           7x   7x 7x     1x 1x 1x 1x         1x       1x 1x     1x         2x 2x 2x   2x 2x     2x 2x 2x 8x 8x 24x             2x   2x 2x   2x               2x 1x 1x       2x   2x 2x 2x               2x                                         3x 3x 1x       2x               2x         1x                     1x                                                   3x 3x 3x  
// API service with axios configuration
 
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { toast } from 'sonner';
import { API_CONFIG, STORAGE_KEYS } from '@/constants';
import { getAdminHeaders } from '@/config/adminPanel';
import { ApiError, ApiResult } from '@/types';
import i18n from '@/lib/i18n';
 
interface HttpError {
  response?: {
    data?: {
      error?: string;
      details?: string;
      timestamp?: string;
    };
  };
  request?: unknown;
  message?: string;
}
 
class ApiService {
  private client: AxiosInstance;
 
  constructor() {
    this.client = axios.create({
      baseURL: API_CONFIG.BASE_URL,
      timeout: API_CONFIG.TIMEOUT,
      headers: {
        'Content-Type': 'application/json'}});
 
    this.setupInterceptors();
  }
 
  private setupInterceptors() {
    // Request interceptor to add auth token and admin panel headers
    this.client.interceptors.request.use(
      (config) => {
        // Respect explicit Authorization set by the caller (e.g., pending admin token)
        const callerAuth = (config.headers as any)?.Authorization || (config.headers as any)?.authorization;
        const token = this.getStoredToken();
        if (!callerAuth && token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
 
        // Add admin panel headers for admin-panel, reseller endpoints, and streaming endpoints
        Iif (typeof FormData !== 'undefined' && config.data instanceof FormData) {
          const headers = (config.headers ?? {}) as any;
          delete headers['Content-Type'];
          delete headers['content-type'];
          config.headers = headers;
        }
 
        const url: string = (config?.url ?? '') as string;
        const isAdminPanelRequest =
          url.startsWith('/api/admin') ||
          url.startsWith('/api/reseller') ||
          url.includes('/stream'); // Add stream endpoints to get proper DRM handling
 
        Iif (isAdminPanelRequest) {
          const adminHeaders = getAdminHeaders();
          const headers = (config.headers ?? {}) as any;
          for (const [k, v] of Object.entries(adminHeaders)) {
            headers[k] = v as any;
          }
          config.headers = headers;
        }
 
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
 
    // Response interceptor for error handling
    this.client.interceptors.response.use(
      (response) => response,
      async (error) => {
        const originalRequest = error.config;
 
        // Handle device disconnected error (401 with "Device disconnected" message)
        Iif (error.response?.status === 401 &&
            error.response?.data?.error === 'Device disconnected') {
          this.clearAuth();
          if (typeof window !== 'undefined') {
            toast.error(i18n.t('common.deviceDisconnectedTitle'), {
              description: i18n.t('common.deviceDisconnectedDescription')
            });
            window.location.href = '/login';
          }
          return Promise.reject(error);
        }
 
        // Handle 401 errors (token expired) - but NOT for refresh endpoint or login endpoint
        if (error.response?.status === 401 &&
            !originalRequest._retry &&
            !originalRequest.url?.includes('/api/auth/refresh') &&
            !originalRequest.url?.includes('/api/auth/login')) {
          originalRequest._retry = true;
    
          try {
            await this.refreshToken();
            const token = this.getStoredToken();
            Eif (token) {
              originalRequest.headers.Authorization = `Bearer ${token}`;
              return this.client(originalRequest);
            }
          } catch (refreshError) {
            // Refresh failed: clear auth and redirect to login
            this.clearAuth();
            this.forceLogoutRedirect();
            return Promise.reject(refreshError);
          }
        }
 
        // If it's a 401 on refresh endpoint, clear auth and redirect
        if (error.response?.status === 401 && originalRequest.url?.includes('/api/auth/refresh')) {
          this.clearAuth();
          this.forceLogoutRedirect();
        }
        
        // Handle 403 Forbidden - user doesn't have permission (token may be for deleted/changed user)
        Iif (error.response?.status === 403 && 
            !originalRequest.url?.includes('/api/auth/') &&
            // Also ignore if it's a 2FA required error - we handle this in AuthContext
            !error.response?.data?.error?.toLowerCase().includes('two-factor')) {
          // Check if this might be a stale token issue
          const errorMsg = error.response?.data?.error?.toLowerCase() || '';
          if (errorMsg.includes('forbidden') || errorMsg.includes('not found') || errorMsg.includes('invalid')) {
            this.clearAuth();
            this.forceLogoutRedirect();
          }
        }
 
        return Promise.reject(error);
      }
    );
  }
 
  private getStoredToken(): string | null {
    Eif (typeof window !== 'undefined') {
      // Try localStorage first
      const localToken = localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
      if (localToken) return localToken;
 
      // Fallback to cookies
      const cookies = document.cookie.split(';');
      for (const cookie of cookies) {
        const [name, value] = cookie.trim().split('=');
        Iif (name === STORAGE_KEYS.AUTH_TOKEN) {
          return value;
        }
      }
    }
    return null;
  }
 
  private setStoredToken(token: string): void {
    Eif (typeof window !== 'undefined') {
      localStorage.setItem(STORAGE_KEYS.AUTH_TOKEN, token);
 
      // Also set in cookies for middleware access
      document.cookie = `${STORAGE_KEYS.AUTH_TOKEN}=${token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`;
    }
  }
 
  private clearAuth(): void {
    Eif (typeof window !== 'undefined') {
      localStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
      localStorage.removeItem(STORAGE_KEYS.USER_DATA);
      // Clear any legacy keys
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_data');
 
      // Also clear cookies under common paths
      const names = [STORAGE_KEYS.AUTH_TOKEN, 'iptv_user_data', 'auth_token', 'user_data'];
      const paths = ['/', '/admin', '/reseller'];
      for (const name of names) {
        document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
        for (const p of paths) {
          document.cookie = `${name}=; path=${p}; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
        }
      }
    }
  }
 
  private forceLogoutRedirect(): void {
    Eif (typeof window !== 'undefined') {
      // Only redirect if not already on login page or public pages
      const publicPaths = ['/login', '/demo', '/redeem', '/forgot-password', '/reset-password'];
      const isPublicPath = publicPaths.some(p => window.location.pathname === p || window.location.pathname.startsWith(`${p}/`));
      
      Iif (!isPublicPath) {
        // Use replace to prevent back button issues
        window.location.replace('/login?session=expired');
      }
    }
  }
 
  private async refreshToken(): Promise<void> {
    const response = await this.client.post('/api/auth/refresh');
    const { token } = response.data;
    this.setStoredToken(token);
  }
 
  private handleError(error: unknown): ApiError {
    const httpError = error as HttpError;
 
    const data: any = httpError.response?.data;
    Eif (data !== undefined) {
      Iif (typeof data === 'string') {
        // Backend returned plain text (e.g., axum handler returning (StatusCode, String))
        return {
          error: i18n.t('common.error'),
          details: data,
          timestamp: new Date().toISOString()};
      }
      // JSON error shape
      return {
        error: data.error || i18n.t('common.error'),
        details: data.details ?? httpError.message ?? i18n.t('common.unexpectedErrorDescription'),
        timestamp: data.timestamp || new Date().toISOString()};
    }
 
    if (httpError.request) {
      return {
        error: i18n.t('common.networkErrorTitle'),
        details: i18n.t('common.networkErrorDescription'),
        timestamp: new Date().toISOString()};
    }
 
    return {
      error: i18n.t('common.error'),
      details: httpError.message || i18n.t('common.unexpectedErrorDescription'),
      timestamp: new Date().toISOString()};
  }
 
  // Generic request method
  async request<T>(config: AxiosRequestConfig): Promise<ApiResult<T>> {
    try {
      const response: AxiosResponse<T> = await this.client(config);
      return {
        success: true,
        data: response.data};
    } catch (error) {
      return {
        success: false,
        error: this.handleError(error)};
    }
  }
 
  // HTTP method helpers
  async get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResult<T>> {
    return this.request<T>({ ...config, method: 'GET', url });
  }
 
  async post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResult<T>> {
    // Special handling for scan-folder endpoint - override timeout completely
    Iif (url.includes('/scan-folder')) {
      const scanConfig = {
        ...config,
        method: 'POST' as const,
        url,
        data,
        timeout: 600000, // Force 10 minutes for scanning operations
      };
      return this.request<T>(scanConfig);
    }
    
    return this.request<T>({ ...config, method: 'POST', url, data });
  }
 
  async put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResult<T>> {
    return this.request<T>({ ...config, method: 'PUT', url, data });
  }
 
  async delete<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResult<T>> {
    return this.request<T>({ ...config, method: 'DELETE', url });
  }
 
  async patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResult<T>> {
    return this.request<T>({ ...config, method: 'PATCH', url, data });
  }
 
  // Auth helpers
  setAuthToken(token: string): void {
    this.setStoredToken(token);
  }
 
  clearAuthToken(): void {
    this.clearAuth();
  }
}
 
// Export singleton instance
export const apiService = new ApiService();
export const apiClient = apiService; // Alias for compatibility
export default apiService;